/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-04-09 13:16:25
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-04-09 16:40:55
 * @FilePath: /lesson26/pipe/testpipe.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <string.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
#define N 2
#define NUM 1024

//child
void Writer(int wfd)
{
    string s="hello,I am child";
    pid_t id=getpid();
    int number=0;

    char buffer[NUM];
    while(true)
    {
        sleep(1);
        // buffer[0]=0;//字符串清空，只是为了提醒阅读代码的人，把这个数组当祖字符串了。
        // snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),id,number++);
        //资源是系统提供的，所以必须使用系统调用接口，system call
        // write(wfd,buffer,strlen(buffer));
        char c='a';
        write(wfd,&c,1);
        //不需要+1，管道是文件！c语言的规定与文件无关!只需要把内容写入!
        // sleep(1);
        number++;
        cout<<number<<endl;
        if(number>=5)
        {
            break;
        }
    }
}

//father
void Reader(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));//sizeof!=strlen
        //sizeof代表缓冲区的大小
        if(n>0)
        {
            buffer[n]=0;//把buffer当字符串使用。0=='\0'
            cout<<"father get a message["<<getpid()<<"]# "<<buffer<<endl;
        }
        else if(n==0)
        {
            cout<<"father read done!\n"<<endl;
            break;
        }
        else break;
        // cout<<"n : "<<n<<endl;
    }
}

int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0)return 1;

    // cout<<"pipefd[0]="<<pipefd[0]<<" , pipefd[1]="<<pipefd[1]<<endl;

    // child->w    father->r
    pid_t id=fork();
    if(id<0)return 2;
    if(id==0)
    {
        //child
        close(pipefd[0]);
        //IPC code
        Writer(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    //father
    close(pipefd[1]);
    //IPC code
    Reader(pipefd[0]);

    pid_t rid=waitpid(id,nullptr,0);
    if(rid<0)return 3;
    close(pipefd[0]);

    sleep(5);

    return 0;
}

